package MovieGuessingGame.player;

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpinnerListModel;
import javax.swing.border.EmptyBorder;
import javax.swing.JList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JSpinner;
import java.awt.Font;
import java.io.IOException;
import MovieGuessingGame.clientutil.*;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

public class GameJFrame extends JFrame implements Runnable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8202054439244602461L;
	private JPanel contentPane;
	// private Socket socket;
	//private SSLSocket socket;
	//private BufferedReader in;
	//private PrintWriter out;
	private ClientSSL client;
	final ArrayList<String> listOfChosen = new ArrayList<String>();
	private TitleCompare titleCompare = null;
	private JList chosenLetterDisplay;
	private JTextField textArea = null;
	private JButton okButton = null;
	private JComboBox wagerAmountBox;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JLabel messageLabel;
	private int unmaskedStarCount = 0;
	boolean didWin = false;
	String totalWins;
	String name;
	String score;
	
	/**
	 * Launch the application.
	 */
	public static void main(final String[] args) {
		try {
			String serverAddress = (args.length == 0) ? "localhost" : args[0];
			ClientSSL fooclient = new ClientSSL();
			fooclient.clientConnect(serverAddress, 8903);
			System.out.println(serverAddress);
			while (true) {

				Thread t = new Thread(new GameJFrame(fooclient));
		        t.start();
				
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	public void run() {
		// TODO Auto-generated method stub
		try {

			// while (true) {

			// GameJFrame frame = new GameJFrame("localhost");
			this.setVisible(true);
			this.setResizable(false);
			this.play();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the frame.
	 * 
	 * @param hash
	 * @throws Exception
	 */
//	public GameJFrame(String serverAddress, byte[] hash) throws Exception {
	public GameJFrame( ClientSSL sslclient) throws Exception {	
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		addWindowListener( 
			    new WindowAdapter() { 
			        public void windowClosing(WindowEvent e) { 
						try {
							client.clientSend("QUIT");
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
			        } 
			    } 
			);
//		System.setProperty("javax.net.ssl.trustStore",
//				"C:\\Users\\Bob\\workspace\\MovieGuessingGame\\pkeystore.jks");
//		SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory
//				.getDefault();
//		socket = (SSLSocket) sslsocketfactory.createSocket(serverAddress, PORT);
//		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//		OutputStream os = socket.getOutputStream();
//		out = new PrintWriter(os, true);
//		os.write(hash);
		
		client = sslclient;
		
		String movieTitle = client.clientReceive();
		name  = client.clientReceive();
		score  = client.clientReceive();
		totalWins  = client.clientReceive();
		this.setTitle("Movie Guessing Game ");
		System.out.println("starting JFrame");
		setBounds(100, 100, 731, 521);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		//String movieTitle = "The";//"The Good, The Bad, and the Ugly";
		titleCompare = new TitleCompare(movieTitle);
		titleCompare.convertToStars();
		JPanel panel = new JPanel();
		contentPane.add(panel);
		String listData[] = { "" };
		String spinnerData[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I",
				"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
				"V", "W", "X", "Y", "Z", };
		panel.setLayout(null);

		chosenLetterDisplay = new JList(listData);
		chosenLetterDisplay.setBounds(0, 0, 66, 437);
		panel.add(chosenLetterDisplay);
		SpinnerListModel model = new SpinnerListModel(spinnerData);
		final JSpinner spinner = new JSpinner(model);
		spinner.setFont(new Font("Tahoma", Font.PLAIN, 16));
		spinner.setBounds(645, 0, 46, 166);
		panel.add(spinner);
		System.out.println(titleCompare.getmMaskedTitle());
		
		textArea = new JTextField(titleCompare.getmMaskedTitle());
		textArea.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		textArea.setBounds(101, 0, 467, 166);
		textArea.setText(titleCompare.getmMaskedTitle());
		textArea.setEditable(false);		
		panel.add(textArea);
		
		okButton = new JButton("Select Displayed Letter");
		okButton.setBounds(283, 363, 163, 59);
		panel.add(okButton);

		// this.pack();
		this.setLocationRelativeTo(null);
		this.setVisible(false);
		this.setVisible(true);
		//starCount = titleCompare.getInitialStarCount();


		JLabel lblChosenLetters = new JLabel("Chosen Letters");
		lblChosenLetters.setBounds(0, 450, 109, 16);
		panel.add(lblChosenLetters);

		JLabel lblMovieTitle = new JLabel("Movie Title");
		lblMovieTitle.setBounds(322, 168, 78, 30);
		panel.add(lblMovieTitle);

		JLabel label_3 = new JLabel("Choose a Letter");
		label_3.setBounds(582, 179, 109, 23);
		panel.add(label_3);

		textField = new JTextField();
		textField.setBounds(452, 207, 116, 22);
		panel.add(textField);
		textField.setColumns(10);

		
		textField_1 = new JTextField(score);
		textField_1.setBounds(452, 242, 116, 22);
		panel.add(textField_1);
		textField_1.setColumns(10);

		
		textField_2 = new JTextField(totalWins);
		textField_2.setBounds(452, 277, 116, 22);
		panel.add(textField_2);
		textField_2.setColumns(10);

		JLabel lblNewLabel = new JLabel("Current Game Score");
		lblNewLabel.setBounds(320, 211, 120, 16);
		panel.add(lblNewLabel);

		JLabel lblNewLabel_1 = new JLabel("Lifetime Points");
		lblNewLabel_1.setBounds(320, 245, 120, 16);
		panel.add(lblNewLabel_1);

		JLabel lblNewLabel_2 = new JLabel("Games Won");
		lblNewLabel_2.setBounds(320, 283, 120, 16);
		panel.add(lblNewLabel_2);

		messageLabel = new JLabel();
		messageLabel.setBounds(101, 328, 467, 22);
		panel.add(messageLabel);
		
		wagerAmountBox = new JComboBox();
		wagerAmountBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "4", "8"}));
		wagerAmountBox.setSelectedIndex(0);
		wagerAmountBox.setBounds(481, 402, 87, 20);
		panel.add(wagerAmountBox);
		
		JLabel lblWagerAmount = new JLabel("Wager Amount");
		lblWagerAmount.setBounds(481, 363, 87, 14);
		panel.add(lblWagerAmount);
		// messageLabel.setColumns(10);

		
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String value = (String) spinner.getValue();
				if (listOfChosen.contains(value)){
					messageLabel.setText("Value Already Chosen");
					messageLabel.updateUI();
				}
				else
				{
					System.out.println("value = " + value);
					listOfChosen.add(value);
					String[] hidden = new String[listOfChosen.size()];
					String[] newStringList = (String[]) listOfChosen.toArray(hidden);
					
					chosenLetterDisplay.setListData(newStringList);
					
					titleCompare.convertToStars();
					System.out.println(titleCompare.getmMaskedTitle());
					
					titleCompare.unMaskStars(newStringList);
					textArea.setText(titleCompare.getmMaskedTitle());
					
					System.out.println(titleCompare.getmMaskedTitle());
					
					//Implement wagering here
					int baseScoreIncrease = titleCompare.getCurrentScoreIncrease(value);
					int adjustedScoreIncrease = 0;
					String item = (String) wagerAmountBox.getSelectedItem();
					System.out.println("Got wager amount: "+item);
					int wagerAmount = Integer.parseInt(  item);
					if ( baseScoreIncrease > 0 ){
						
						adjustedScoreIncrease = baseScoreIncrease * wagerAmount;
					}
					else {
						if (wagerAmount > 1){
							adjustedScoreIncrease = 0 - wagerAmount;
						}
						else {
							adjustedScoreIncrease = 0;
						}
					}
					unmaskedStarCount += adjustedScoreIncrease;
					
					textField.setText(new Integer(unmaskedStarCount).toString());
					 
					textField.updateUI();
					
					didWin = titleCompare.didWin(titleCompare.getmMaskedTitle());
					if (didWin){
						messageLabel.setText("You won");
						messageLabel.updateUI();
						try {
							client.clientSend("DEFEAT" + textField.getText());
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					try {
						client.clientSend("MOVE " + value);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					okButton.setEnabled(false);
				}
			}
		});
		
		this.setVisible(false);
		this.setVisible(true);

	}

	public void play() throws Exception {
		String response;
		boolean gameOver = false;
		try {
			response = client.clientReceive();
			char mark = 0;
			String markStr = null;
			if (response.startsWith("WELCOME")) {
				mark = response.charAt(8);

				markStr = String.valueOf(mark);

				this.setTitle("Movie Guessing Game Player" + mark);
				if (mark == '2') {
					okButton.setEnabled(false);
				}
			}
			while (true) {
				response = client.clientReceive();
				System.out.println("respnse "+ response);
				
				if (response == null ){
					break;
				}
				
				if (response.startsWith("VALID_MOVE")) {
					//if (!gameOver)
					messageLabel.setText("Valid move, please wait");

				} else if (response.startsWith("OPPONENT_MOVED")) {
					String selection = response.substring(15);
					listOfChosen.add(selection);
					String[] hidden = new String[listOfChosen.size()];
					String[] newStringList = (String[]) listOfChosen
							.toArray(hidden);
					chosenLetterDisplay.setListData(newStringList);
					titleCompare.convertToStars();
					System.out.println(titleCompare.getmMaskedTitle());
					titleCompare.unMaskStars(newStringList);
					textArea.setText(titleCompare.getmMaskedTitle());
					System.out.println(titleCompare.getmMaskedTitle());
					okButton.setEnabled(true);
					//if (!gameOver)
					messageLabel.setText("Opponent moved, your turn");
				} else if (response.startsWith("VICTORY")) {
					messageLabel.setText("You win!");
					gameOver = true;
					//break;
				} else if (response.startsWith("DEFEAT")) {
					gameOver = true;
					messageLabel.setText("You lose");
					
					//break;
				} else if (response.startsWith("TIE")) {
					gameOver = true;
					messageLabel.setText("You tied");
					//break;
				} else if (response.startsWith("MESSAGE")) {
					//if (!gameOver)
					messageLabel.setText(response.substring(8));
				}
			}
			// output("QUIT");
		} finally {
			client.closeSocket();
		}
	}
}
